package com.yxc.mambalibrary.http;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.util.HashMap;

/**
 * CallBackHandler
 * Created by robin on 15/12/4.
 *
 * @author yangxc
 */
public class CallBackHandler extends Handler {

    public final String TAG = "CallBackHandler";

    public final static int EVENT_TYPE_START = 0;
    public final static int EVENT_TYPE_SUCCESS = 1;
    public final static int EVENT_TYPE_FAILURE = 2;

    public final static String KEY_REQUEST = "request";
    public final static String KEY_RESPONSE = "response";
    public final static String KEY_ERROR = "error";

    private IRequestCallBack callBack;

    public CallBackHandler(Looper looper, IRequestCallBack callBack) {
        super(looper);
        this.callBack = callBack;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (callBack == null) {
            Log.w("CallBackHandler WARNING", "CallBack is null");
            return;
        }
        HashMap<String, Object> messageObj = null;
        try {
            messageObj = (HashMap<String, Object>) msg.obj;
        } catch (Exception e) {
            Log.e("CallBackHandler ERROR", "CallBackHandler 内部错误 : " + e.toString());
            return;
        }
        IRequest request = (IRequest) messageObj.get(KEY_REQUEST);
        IResponse response = (IResponse) messageObj.get(KEY_RESPONSE);
        RequestException error = (RequestException) messageObj.get(KEY_ERROR);
        switch (msg.what) {
            case EVENT_TYPE_START:
                requestStart(request);
                break;
            case EVENT_TYPE_SUCCESS:
                if (response.hasError()){
                    requestFailure(request, response.throwExceptionWhenHasError());
                } else {
                    requestSuccess(request, response);
                }
                break;
            case EVENT_TYPE_FAILURE:
                requestFailure(request, error);
                break;
            default:
                break;
        }
    }

    private void requestStart(IRequest request){
        Log.i(TAG, "******************* Request " + request.getTag() + " start ********************");
        callBack.onStart(request);
    }

    private void requestSuccess(IRequest request, IResponse response){
        Log.i(TAG, "******************* Request " + request.getTag() + " success *****************");
        Log.i(TAG, "Response : " + response.getResult().toString());
        callBack.onSuccess(request, response);
    }

    private void requestFailure(IRequest request, RequestException error){
        Log.i(TAG, "******************* Request " + request.getTag() + " failure *****************");
        Log.i(TAG, "Exception : " + error.getMessage());
        callBack.onFailure(request, error);
    }
}
